package com.toplabs.unashu.common.utils;

import cn.hutool.json.JSONUtil;
import com.toplabs.unashu.common.Constants;
import com.toplabs.unashu.common.response.CommonResponse;
import com.toplabs.unashu.common.response.StatusCode;
import com.toplabs.unashu.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author toplabs
 * @since 2022/08/09
 * <p>This java file was created by toplabs in 2022/08/09.
 * The following is the description information about this file:</p>
 * <p>description: api util</p>
 */
@Slf4j
public class ApiUtils {
    private ApiUtils() {
        throw new IllegalStateException("Utility class");
    }

    public static void result(HttpServletResponse response, int code, String message) {
        response.setContentType(Constants.RESPONSE_CONTENT_TYPE);
        try (PrintWriter writer = response.getWriter()) {
            writer.write(JSONUtil.toJsonStr(CommonResponse.result(code, message)));
        } catch (IOException e) {
            log.error("response exception: ", e);
            throw new ServiceException(code, "response exception: " + e);
        }
    }

    public static void result(HttpServletResponse response, StatusCode statusCode) {
        result(response, statusCode.getCode(), statusCode.getMessage());
    }

    public static Map<String, String> getUrlParams(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>(request.getParameterMap().size());
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String pk = parameterNames.nextElement();
            String pv = request.getParameter(pk);
            params.put(pk, pv);
        }
        return params;
    }

    public static String convertToString(InputStream is) {
        StringBuilder sb = new StringBuilder();
        String line;
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            log.error("data stream conversion exception: ", e);
            throw new ServiceException("data stream conversion exception: " + e.getMessage());
        }
        return sb.toString();
    }
}
